import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Solution971 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    boolean can=true;
    int cur=0;

    public List<Integer> flipMatchVoyage(TreeNode root, int[] voyage) {
        List<Integer> ans=new ArrayList<>();
        dfs(root,voyage,ans);
        if (can){
            return ans;
        }else {
            return new ArrayList<>(Collections.singletonList(-1));
        }
    }

    private void dfs(TreeNode root, int[] voyage, List<Integer> ans) {
        if (root.val!=voyage[cur]){
            can=false;
            return;
        }
        if (root.left!=null){
            cur++;
            if (root.left.val!=voyage[cur]){
                ans.add(root.val);
                TreeNode t=root.left;
                root.left=root.right;
                root.right=t;
            }
            if (root.left!=null){
                dfs(root.left,voyage,ans);
            }else {
                can=false;
                return;
            }
            if (can && root.right!=null){
                cur++;
                dfs(root.right,voyage,ans);
            }
        }else {
            if (root.right!=null){
                cur++;
                dfs(root.right,voyage,ans);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new Solution971().flipMatchVoyage(new TreeNode(1,new TreeNode(2,new TreeNode(3),null),null),new int[]{1,3,2}));
    }
}
